/**
 * 手写 Promise.all
 */

const PromiseAll = function PromiseAll<T>(iterators:Array<T>) {

  let results:Array<T> = [];
  let promiseCount = 0;
  let promisesLength = iterators.length;

  return new Promise((res, rej) => {
    for(let item of iterators) {
      Promise.resolve(item).then(data => {
        // console.log(data);
        
        promiseCount++;
        results.push(data);
        // 当所有函数都正确执行了，resolve输出所有返回结果。
        if (promiseCount === promisesLength) {
          return res(results);
        }
      }).catch(err => {
        return rej(err);
      })
    }
  });
};

export default PromiseAll;

